package com.kanshu.ksgb.fastread.doudou.common.business.ad;

import android.app.Activity;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd;
import com.inmobi.ads.InMobiInterstitial;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.dialog.ReaderAdDialog;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigBean;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigs;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.toutiao.StringUtils;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.toutiao.WeakHandler;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVDefaultManager;
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.SettingManager;
import com.kanshu.ksgb.fastread.doudou.common.util.NetUtils;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Timer;
import java.util.TimerTask;

import static com.kanshu.ksgb.fastread.doudou.common.business.ad.dialog.ReaderAdDialog.PLAY_AD;


/**
 * Title:
 * Description: 阅读页视频广告播放辅助类
 * Copyright: Copyright(c)2018
 * Company: 看书网
 * CreateTime: 2018/10/22 10:26
 *
 * @author EvanHe
 * @version 3.0
 */
public class ReaderAdHelper implements ReaderAdDialog.ReaderAdListener, WeakHandler.IHandler {
    private static final int MSG_GO_MAIN = 1;
    private static final long RESET_TIME = 0;
    private Activity mActivity;
    private long startTime;
    private ReaderAdDialog mDialog;
    private Object mRewardVideoAd = null;

    private Timer mTimer;
    private TimerTask mTimerTask;
    private TextView mOkay;
    private int mTime = 3;
    private WeakHandler mHandler = new WeakHandler(this);
    private boolean mIsFirstFetchAd = false;
    public boolean mIsStop = false;

    public ReaderAdHelper(Activity activity) {
        mActivity = activity;
    }

    //填坑，调用广告的时候会执行onResume()方法，防止重复调用
    public void restartReadTime() {
        if (mIsStop) {
            startReadTime();
        }
    }

    public void startReadTime() {
        startTime = System.currentTimeMillis();
    }

    public void countReadTime() {
        long endTime = System.currentTimeMillis();
        long readTime = StringUtils.getDistanceTime(startTime, endTime);
        long historyReadTime = SettingManager.getInstance().getReadTime();
        SettingManager.getInstance().saveReadTime(readTime + historyReadTime);
    }

    public void showAdDialog() {
        //wifi环境下，展示视频广告
        if (NetUtils.getNetConnectType(Xutils.getContext()) != NetUtils.WIFI) return;
        ADConfigBean config = ADConfigs.showAD(String.valueOf(ADConfigBean.POSITION_READER_DIALOG_VIDEO));
        //刚进入阅读器不提示
        if (config == null || !mIsFirstFetchAd) {
            mIsFirstFetchAd = true;
            return;
        }
        String serverReadTime =  MMKVDefaultManager.getInstance().getServerReadTime();
        String str[] = serverReadTime.split("#");
        if (str.length > 1) {
            long endTime = System.currentTimeMillis();
            long readTime = StringUtils.getDistanceTime(startTime, endTime);
            long historyReadTime = SettingManager.getInstance().getReadTime();
            Log.d("evan", "serverTime: " + str[0] + "   readTime: " + readTime + "    historyTime: " + historyReadTime + "   startTime: " + startTime);
            if (Long.parseLong(str[0]) <= (readTime + historyReadTime)) {//1541390077790
                loadAd();
                mDialog = ReaderAdDialog.show(mActivity, str[0], str[1]);
                if(mDialog != null) {
                    mDialog.setReadAdListener(this);
                }
                //判断广告视频强制播放时，倒计时6秒自动播放广告
                if (TextUtils.equals(str[1], PLAY_AD)) {
                    mTimerTask = new TimerTask() {
                        public void run() {
                            Log.d("evan", "6秒自动播放广告");
                            playVideo();
                        }
                    };
                    mTimer = new Timer(true);
                    mTimer.schedule(mTimerTask, 6000);
                }
            }
        }
    }

    @Override
    public void playAdVideo(TextView view) {
        mOkay = view;
        mOkay.setEnabled(false);
        playVideo();
    }

    private void playVideo() {
        closeAutoPlayTimer();
        mActivity.runOnUiThread(() -> {
            if (mRewardVideoAd != null) {
                playAd();
                if(mDialog != null) {
                    mDialog.dismiss();
                }
            } else {
                //没有获取到广告资源，开始倒计时3秒关闭弹窗
                mTime = 3;
                if (mOkay != null) {
                    mOkay.setText(mActivity.getString(R.string.reader_play_ad_text1, mTime));
                }
                Message message = mHandler.obtainMessage(MSG_GO_MAIN);
                mHandler.sendMessageDelayed(message, 1000);
            }
        });
    }

    /**
     * 获取到广告视频资源，立即播放广告
     */
    private void playAd() {
        if (mRewardVideoAd instanceof InMobiInterstitial) {
            ((InMobiInterstitial) mRewardVideoAd).show();
        } else if (mRewardVideoAd instanceof TTFullScreenVideoAd) {
            ((TTFullScreenVideoAd) mRewardVideoAd).showFullScreenVideoAd(mActivity);
        }
    }


    @Override
    public void continueRead() {
        closeAutoPlayTimer();
    }

    private void closeAutoPlayTimer() {
        startReadTime();
        SettingManager.getInstance().saveReadTime(RESET_TIME);
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
        if (mTimer != null) {
            mTimer.cancel();
            mTimer.purge();
            mTimer = null;
        }
    }

    private void loadAd() {
        AdUtils.fetchAdUtil(mActivity, null, null, ADConfigBean.POSITION_READER_DIALOG_VIDEO, AdStyleBean.REWARDED_FULL_SCREEN_VIDEO_STYLE, 0, new BaseAdListener() {
            @Override
            public void onBackAd(@NotNull Object ad) {
                mRewardVideoAd = ad;
            }

            @Override
            public void onADClosed() {
            }

            @Override
            public void onAdClicked() {
            }

            @Override
            public void onAdLoadFailed() {
            }

            @Override
            public void onAdLoadSucceeded(@Nullable View view) {
            }
        });
    }

    public void destroyAd() {
        if (mRewardVideoAd != null) {
            mRewardVideoAd = null;
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
    }

    @Override
    public void handleMsg(Message msg) {
        //3秒倒计时关闭弹窗
        if (msg.what == MSG_GO_MAIN) {
            mTime--;
            Log.e("evan", "time: " + mTime);
            if (mOkay != null) {
                mOkay.setText(mActivity.getString(R.string.reader_play_ad_text1, mTime));
            }
            if (mTime > 0) {
                Message message = mHandler.obtainMessage(MSG_GO_MAIN);
                mHandler.sendMessageDelayed(message, 1000);  // send message
            } else {
                if (mRewardVideoAd != null) {
                    playAd();
                }
                if(mDialog != null) {
                    mDialog.dismiss();
                }
            }
        }
    }
}


